import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:myapp/src/services/floating_window_service.dart' as ai_service;
import 'package:flutter/services.dart';

class FloatingBall extends StatefulWidget {
  const FloatingBall({super.key});

  @override
  State<FloatingBall> createState() => _FloatingBallState();
}

class _FloatingBallState extends State<FloatingBall> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //初始化，必不可少。不然无法正常进行单位转换。
    ScreenUtils.init(context);

    ///FlutterOverlayWindow.showOverlay()里的宽高，单位是px,而flutter是dp;
    ///所以，为了保持宽高一致，我们需要把px转换为dp
    var _width = ScreenUtils.pixelToDp(ai_service.FloatingWindowService.width);
    var _height = ScreenUtils.pixelToDp(ai_service.FloatingWindowService.height);
    //print("================宽：${_width}\t高：${_height}");
    return GestureDetector(
      onTap: () async {
        print('悬浮球被点击');
        try {
          // // 发送启动应用的信号
          // await FlutterOverlayWindow.shareData("launch_app");
          // print('已发送启动应用信号');
          // // 延迟一下再关闭悬浮窗，确保信号能发送出去
          // await Future.delayed(const Duration(milliseconds: 100));

          //启动应用，如果应用已经打开，不会重复打开。
          AioPlugin.startOneself(context);
          //延迟一下再关闭悬浮窗，确保能启动应用。加上之后，亲测有效，能百分百打开应用。
          await Future.delayed(const Duration(milliseconds: 100));
          //关闭悬浮窗
          //await FlutterOverlayWindow.closeOverlay();
          //fixme 关闭悬浮球，统一调用这个方法。
          ai_service.FloatingWindowService.closeFloatingWindow(isForce: true);
          print('悬浮窗已关闭');
        } catch (e) {
          print('悬浮球点击处理出错: $e');
        }
      },
      child: Container(
        color: Colors.transparent,
        alignment: Alignment.center,
        //宽高，不设置，默认就是充满父容器的。
        // width: _width,
        // height: _height,
        child: _ball(context, _width, _height),
      ),
    );
  }

  ///悬浮球
  Widget _ball(BuildContext context, double width, double height) {
    // 主图标
    var logo = Center(
      child: Icon(
        Icons.touch_app,
        color: Colors.white,
        size: 48,
      ),
    );
    return Container(
      width: width / 6 * 5,
      height: height / 6 * 5,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            const Color(0xFF6200EE).withOpacity(0.45),
            const Color(0xFF3700B3).withOpacity(0.3),
          ],
        ),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF6200EE).withOpacity(0.3),
            blurRadius: width / 25,
            spreadRadius: 2,
          ),
        ],
      ),
      child: LibUi.getBadge("10", logo),
    );
  }
}
